import { BadRequestException, PipeTransform } from '@nestjs/common'

interface ParseArrayOptions {
  items: any
  separator?: string
}

export class ParseArrayPipe implements PipeTransform<string, any[]> {
  constructor(private readonly options?: ParseArrayOptions) {

  }

  transform(value: string): any[] {
    if (!value) return []
    const { items = String, separator = ',' } = this.options
    // 以 separator 为切割
    const values = value.split(separator).map(item => {
      if (items === String) { // 转换为字符串
        return item
      } else if (items === Boolean) { // 转换为布尔
        return Boolean(item)
      } else if (items === Number) { // 转换为数字
        return Number(item)
      }
    })

    return values
  }
}
